package com.coffee.soft.service.impl;

import com.coffee.soft.config.Config;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author:LiuRuidong
 * @Description:
 * @Date: Created in 2:20 2018/2/6
 * @Modified By:
 */
@Service
public class QiNiuService {
    //设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = Config.getValue("qinNiu.ACCESS_KEY"); //这两个登录七牛 账号里面可以找到
    String SECRET_KEY = Config.getValue("qinNiu.SECRET_KEY");

    //要上传的空间
    String bucketname = Config.getValue("qinNiu.bucketname"); //对应要上传到七牛上 你的那个路径（自己建文件夹 注意设置公开）
    String URL=Config.getValue("qinNiu.picURL");
    //上传到七牛后保存的文件名
    // String key = "daimo6.png";
    //上传文件的路径
    //密钥配置
    //创建上传对象
    Configuration cfg = new Configuration(Zone.zone0());
    UploadManager uploadManager = new UploadManager(cfg);


    /**
     * 上传图片到七牛云
     * @param file（本地文件路径）
     * @return
     * @throws IOException
     */
    public String upload(MultipartFile file) throws IOException {
        DefaultPutRet putRet = null;
        String newKey = null;
        try {
            //密钥配置
            String key = file.getOriginalFilename();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            //增加文件后缀名的时间戳
            String str = simpleDateFormat.format(new Date());
            newKey = key.substring(0 ,key.indexOf(".")) + "-"+str + key.substring(key.lastIndexOf("."));
            InputStream inputStream = file.getInputStream();
            byte[] bytes = readStream(inputStream);
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String upToken = auth.uploadToken(bucketname);
            Response res = uploadManager.put(byteInputStream ,newKey,upToken,null, null);
            //解析上传成功的结果
            putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(putRet);
        System.out.println(URL+newKey);
        return URL+newKey;
    }

    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while((len = inStream.read(buffer)) != -1){
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }


    /**
     * 删除一个七牛云上的图片
     * @param path 图片在七牛云上的路径
     * @throws IOException
     */
    public void deletePic(String path)throws IOException {
        //...其他参数参考类注释
        String key = path.substring(path.lastIndexOf("/") + 1);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucketname , key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }

    /**
     * 批量删除七牛云上的图片
     */
    public void deleteNum(String [] str){
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            //单次批量请求的文件数量不得超过1000
            String[] keyList = new String[str.length];
            for(int i=0;i<str.length;i++){
                String key = str[i].substring(str[i].lastIndexOf("/") + 1);
                keyList[i]=key;
            }
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(bucketname, keyList);
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < keyList.length; i++) {
                BatchStatus status = batchStatusList[i];
                String key = keyList[i];
                System.out.print(key + "\t");
                if (status.code == 200) {
                    System.out.println("delete success");
                } else {
                    System.out.println(status.data.error);
                }
            }
        } catch (QiniuException ex) {
            System.err.println(ex.response.toString());
        }
    }

    public static void main(String[] args) {
   /*     String FilePath = "C:\\Users\\Public\\Pictures\\Sample Pictures\\1.jpg";
        String st = null;
        try {
            *//*st = new QiNiuService().upload(FilePath);*//*
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(st);
    }*/

    }
}
